package com.shanghaionstar.notification.service.impl;

import android.content.Context;

import com.onstar.cn.api.PublicService;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.http.ResponseHandler;
import com.onstar.cn.framework.network.http.Sender;
import com.onstar.cn.mag.publicService.DeviceInfoEntity;
import com.onstar.cn.mag.publicService.SessionEntity;
import com.shanghaionstar.notification.service.InterfaceService;
import com.shanghaionstar.notification.service.RequestParams;
import com.shanghaionstar.utils.NetConnectUtil;

/**
 * 业务逻辑操作
 * 
 * @author 7828wc
 * 
 */
public class InterfaceServiceImpl implements InterfaceService {
//	private BOSHConnection connection = null;
	private boolean isLogin = false;
	private RequestParams params;
	private Context context;
	private String deviceId;
	private int retryTimes = 2;
	private String serverURL;

	public InterfaceServiceImpl(Context ctx, String serverURL) {
		this.context = ctx;
		this.serverURL = serverURL;
	}

	@Override
	public boolean connect(RequestParams para) {
//		try {
//
//			if (para == null) {
//				this.params = RequestParams.getDefaultParams(context);
//			} else {
//				this.params = para;
//			}
//			String host = !isNull(params.getHost()) ? params.getHost() : NotificationConstants.HOST;
//			Integer port = !isNull(params.getPort() + "") ? params.getPort() : NotificationConstants.PORT;
//			// BOSHConfiguration connectionConfig = new BOSHConfiguration(host,
//			// port);
//			BOSHConfiguration connectionConfig = new BOSHConfiguration(false, host, port, "/xmpp/http-bind/",
//					params.getDeviceId());
//			connectionConfig.setReconnectionAllowed(true);
//			connectionConfig.setSendPresence(true);
//			// SASLAuthentication.supportSASLMechanism("PLAIN",0);
//			connectionConfig.setSelfSignedCertificateEnabled(false);
//			connectionConfig.setSecurityMode(SecurityMode.disabled);
//			connectionConfig.setSASLAuthenticationEnabled(false);
//			connectionConfig.setCompressionEnabled(false);
//			connection = new BOSHConnection(connectionConfig);
//			new Thread(new Runnable() {
//				@Override
//				public void run() {
//					try {
//						connection.connect();// 寮?惎杩炴帴
//						// connection.login(params.getDeviceId(),
//						// params.getAppScrcet(), params.getDeviceToken());
//						String token = (params.getDeviceToken() == null || "".equals(params.getDeviceToken())) ? ""
//								: "@" + params.getDeviceToken();
//						String secondParam = params.getAppScrcet();// + token;
//						connection.login(params.getDeviceId(), secondParam);
////						 connection.login("admin","admin");
//						ChatManager chatManager = connection.getChatManager();
//						chatManager.addChatListener(InterfaceServiceImpl.this);
//						isLogin = true;
//					} catch (Exception e) {
//						e.printStackTrace();
//						LogManager.getInstance().e(e.getMessage());
//						isLogin = false;
//						if (params.isAutoRetry()) {
//							if (retryTimes-- > 0) {
//								connect(params);
//							}
//						}
//					}
//				}
//			}).start();
//			return isLogin;
//		} catch (Exception e) {
//			LogManager.getInstance().e(e.getMessage());
//		}
		return false;
	}

	@Override
	public boolean disconnect() {
//		try {
//			if (connection != null) {
//				connection.disconnect();
//			}
//			return true;
//		} catch (Exception e) {
//			e.printStackTrace();
//			return false;
//		}
		return false;
	}

//	@Override
//	public void chatCreated(Chat arg0, boolean arg1) {
//		arg0.addMessageListener(new MessageListener() {
//			@Override
//			public void processMessage(Chat arg0, Message msg) {
//				Intent intent = new Intent();
//				intent.setAction(NotificationConstants.RECEIVER_NAME);
//				String[] message = new String[] { msg.getFrom(), msg.getBody() };
//				XMPPMessage sendMsg = new XMPPMessage();
//				// String tempMsg
//				// ="{\"accessSource\":null,\"account\":\"1201759916\",\"browser\":null,\"channel\":null,\"device\":null,\"ip\":null,\"os\":null,\"phone\":null,\"puserId\":\"ONSTARM17643142\",\"role\":\"PROXY\",\"status\":\"success\",\"time\":\"1426492973605\",\"body\":\"F2201\",\"version\":\"4.7.0\",\"vin\":\"LSGGF67B9D026009C\",\"wechat\":null}";
//				sendMsg = sendMsg.parseResponse(message[1]);
//				sendMsg.setMsg(sendMsg.getMsg());
//				sendMsg.setJumpFlag(sendMsg.getJumpFlag());
//				sendMsg.setLink(sendMsg.getLink());
//				Bundle bundle = new Bundle();
//				bundle.putSerializable("message", sendMsg);
//				intent.putExtras(bundle);
//				context.sendBroadcast(intent);
//
//			}
//		});
//	}

	private static boolean isNull(String value) {
		return (value == null) || ("".equals(value.trim())) || ("null".equals(value.trim()));
	}

	@Override
	@Request(heads = @HeadsValue(accept = HttpAccept.JSON) , method = HttpMethod.PUT)
	public void saveDeviceInfo(DeviceInfoEntity req, ResponseHandler responseHandler) {
		RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
		PublicService publicService = new PublicService(serverURL);
		DeviceInfoEntity deviceInfoEntity = new DeviceInfoEntity();
		deviceInfoEntity.setDeviceID(req.getDeviceID());
		deviceInfoEntity.setDeviceType(req.getDeviceType());
		deviceInfoEntity.setDeviceToken(req.getDeviceToken());
		deviceInfoEntity.setIsAlert(req.getIsAlert());
		deviceInfoEntity.setIsBind(req.getIsBind());
		deviceInfoEntity.setIsNotification(req.getIsNotification());
		publicService.deviceInfo(requestEntity, deviceInfoEntity);
		
		Sender sender = new Sender();
		sender.send(requestEntity, responseHandler, getClass(), "saveDeviceInfo", DeviceInfoEntity.class, ResponseHandler.class);
	}

	@Override
	@Request(heads = @HeadsValue(accept = HttpAccept.JSON) , method = HttpMethod.PUT)
	public void saveSession(SessionEntity req, ResponseHandler responseHandler) {
		RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
		PublicService publicService = new PublicService(serverURL);
		publicService.saveSession(requestEntity, req);
		Sender sender = new Sender();
		sender.send(requestEntity, responseHandler, getClass(), "saveSession", SessionEntity.class, ResponseHandler.class);
	}
}
